package com.crazyhat.crazyhat.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crazyhat.crazyhat.attribute.ClubPositionEnum;
import com.crazyhat.crazyhat.attribute.ClubStatusEnum;
import com.crazyhat.crazyhat.attribute.TokenPayloadEnum;
import com.crazyhat.crazyhat.entity.Club;
import com.crazyhat.crazyhat.entity.Participation;
import com.crazyhat.crazyhat.mapper.ClubMapper;
import com.crazyhat.crazyhat.mapper.ParticipationMapper;
import com.crazyhat.crazyhat.mapper.UserMapper;
import com.crazyhat.crazyhat.pojo.Manage;
import com.crazyhat.crazyhat.service.IManageService;
import com.crazyhat.crazyhat.utils.ThreadLocalUtil;
import com.github.yulichang.query.MPJQueryWrapper;

@Service
public class ManageServiceImpl implements IManageService {

    @Autowired
    private ParticipationMapper participationMapper;

    @Autowired
    private ClubMapper clubMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取个人管理的社团
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<Manage> getPersonalManagePlus(int pageNum, int pageSize){
        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get(TokenPayloadEnum.StudentId.getValue());

        MPJQueryWrapper<Participation> mpjQueryWrapper=new MPJQueryWrapper<>();
        mpjQueryWrapper
            .selectAll(Participation.class)
            .select("u.club_name","u.club_id","u.logo_url")
            .leftJoin("club u on u.club_id = t.club_id")
            .eq("t.student_id", studentId)
            .in("t.club_position", ClubPositionEnum.LEADER,ClubPositionEnum.SECOND_LEADER);

        Page<Manage> page = new Page<>(pageNum, pageSize);
        Page<Manage> manageList=participationMapper.selectJoinPage(page,Manage.class, mpjQueryWrapper);

        return manageList;
    }

    @Override
    public Page<Manage> getPersonalManage(int pageNum, int pageSize) {


        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get("studentId");

        // 创建查询条件，查询用户管理的社团参与记录
        QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                .and(wrapper -> wrapper
                        .eq("club_position", ClubPositionEnum.LEADER)
                        .or()
                        .eq("club_position", ClubPositionEnum.SECOND_LEADER));

        // 分页查询 Participation 记录
        Page<Participation> participationPage = new Page<>(pageNum, pageSize);
        Page<Participation> resultPage = participationMapper.selectPage(participationPage, queryWrapper);

        // 获取社团ID列表
        List<Integer> clubIds = resultPage.getRecords().stream()
                .map(Participation::getClubId)
                .collect(Collectors.toList());

        if (clubIds.isEmpty()) {
            return new Page<>();
        }

        QueryWrapper<Club> clubQueryWrapper = new QueryWrapper<>();
        clubQueryWrapper.in("club_id", clubIds)
                .and(wrapper->wrapper
                        .eq("club_status", ClubStatusEnum.Open)
                        .or()
                        .eq("club_status",ClubStatusEnum.RestrictJoining)
                        .or()
                        .eq("club_status",ClubStatusEnum.InReview)
                );

        List<Club> clubs = clubMapper.selectList(clubQueryWrapper);

        // 将社团信息和用户信息转化为 Manage 对象
        List<Manage> manages = resultPage.getRecords().stream().map(participation -> {
            Club club = clubs.stream()
                    .filter(c -> c.getClubId().equals(participation.getClubId()))
                    .findFirst()
                    .orElse(null);
            if (club != null) {
                Manage manage = new Manage();
                manage.setClubName(club.getClubName());
                manage.setClubId(club.getClubId());
                manage.setUserName(userMapper.selectById(studentId).getName());
                manage.setStudentId(studentId);
                manage.setClubPosition(participation.getClubPosition().name());
                return manage;
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        // 创建分页结果
        Page<Manage> managePage = new Page<>(pageNum, pageSize);
        managePage.setRecords(manages);
        managePage.setTotal(resultPage.getTotal());

        return managePage;
    }


    @Deprecated
    @Override
    public List<Manage> getPersonalManageList() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get("studentId");

        // 创建查询条件
        QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                .and(wrapper -> wrapper.eq("club_position", ClubPositionEnum.LEADER)
                        .or()
                        .eq("club_position", ClubPositionEnum.SECOND_LEADER));

        // 查询用户管理的 Participation 记录
        List<Participation> participations = participationMapper.selectList(queryWrapper);

        // 获取社团ID列表
        List<Integer> clubIds = participations.stream()
                .map(Participation::getClubId)
                .collect(Collectors.toList());

        // 查询社团信息
        List<Club> clubs = clubMapper.selectBatchIds(clubIds);

        // 将社团信息和用户信息转化为 Manage 对象
        List<Manage> manages = participations.stream().map(participation -> {
            Club club = clubs.stream()
                    .filter(c -> c.getClubId().equals(participation.getClubId()))
                    .findFirst()
                    .orElse(null);
            if (club != null) {
                Manage manage = new Manage();
                manage.setClubName(club.getClubName());
                manage.setClubId(club.getClubId());
                manage.setUserName(userMapper.selectById(studentId).getName());
                manage.setStudentId(studentId);
                manage.setClubPosition(participation.getClubPosition().name());
                return manage;
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return manages;
    }
}
